// import DeviceBridge, { dvc } from "../../../Core/Bridges/DeviceBridge";
// import { DM } from "../../../Core/Mgr/dataManager";

import AUpgrade, { UpgradeEvent } from "../Abstract/AUpgrade";
import Downloader from "../Net/Downloader";
import Http, { HttpType } from "../Net/Http";


declare let Core: any;

const { ccclass, property } = cc._decorator;
@ccclass
export default class GameUpgrade extends AUpgrade {
    protected RemoveCallback(url: string) {
        Downloader.obj.RemoveCallback(url);
    }
    protected Download(url: string, fullName: string, md5: string, onSucceed: Function, retry?: boolean, onError?: Function, onProgress?: Function) {
        Downloader.obj.Download(url, fullName, md5, onSucceed, retry, onError, onProgress);
    }

    protected storagePath(ver: string): string {
        return jsb.fileUtils.getWritablePath() + ver + ".zip";
    }
    protected get VerPath(): string {
        return "ver.txt";
    }

    @property(cc.Node)
    private uRoot: cc.Node = null;

    @property(cc.Sprite)
    private uBar: cc.Sprite = null;

    @property({ type: cc.Label, tooltip: " 完成度 " })
    private uCompletion: cc.Label = null;

    @property(cc.Label)
    private uVer: cc.Label = null;

    @property(cc.Label)
    private labTestInfo: cc.Label = null;

    protected onLoad(): void {
        // TODO:
        // this.uVer.string = `app :${dvc.obj.AppVer} res :${DeviceBridge.obj.Core}.${DeviceBridge.obj.Res}`;
        this.uRoot.active = false;
        // this.Go();
    }

    protected OnDecompressDone() {
        Core.Instance().Restart();
        cc.game.restart();
    }

    public Go() {
        let url = "";
        let param = {};

        // let url = DM.instance().gameConfig.http2Server;
        // let param = DeviceBridge.obj.PackageInfo();
        let self = this;
        this.Analysis((evt: UpgradeEvent, arg1, arg2) => {
            switch (evt) {
                case UpgradeEvent.Nothing:
                    self.OnDecompressDone();
                    break;
                case UpgradeEvent.Pkg:
                    self.uRoot.active = true;
                    if (cc.sys.os == cc.sys.OS_ANDROID || cc.sys.os == cc.sys.OS_WINDOWS) {
                        self.Apk(arg1, arg2);
                    }
                    else if (cc.sys.os == cc.sys.OS_IOS) {
                        self.Ipa(arg1);
                    }
                    break;
                case UpgradeEvent.Assets:
                    self.uRoot.active = true;
                    self.Assets(arg1);
                    self.DownloadAssets();
                    break;
            }
        }, url, param);
    }

    protected OnProgress() {
        let prog = this.mReceived / this.mExpected;

        if (this.uBar) {
            this.uBar.fillRange = Math.min(prog * 0.85 + 0.15, 1);
        }

        if (this.uCompletion) {
            const nowKb = this.getBytes(this.mReceived);
            const totalKb = this.getBytes(this.mExpected)
            this.uCompletion.string = "更新进度:" + ` ${nowKb}/${totalKb}    ${this.mReceived}/${this.mExpected}`;
        }
    }

    protected getBytes(byte) {
        const kb = byte / 1024;
        const mb = kb / 1024;
        const gb = mb / 1024;

        if (gb > 1) {
            return gb.toFixed(2) + "GB";
        }
        if (mb > 1000) {
            return gb.toFixed(2) + "GB";
        }
        if (mb > 1) {
            return mb.toFixed(2) + "MB";
        }
        if (kb > 1000) {
            return mb.toFixed(2) + "MB";
        }
        if (kb < 1) {
            return kb.toFixed(2) + "KB";
        }
        return kb.toFixed(2) + "KB"
    }


    private onBtnClick(event: cc.Event.EventTouch, data: string) {
        if (data == "checkUpdate") {
            this.loadTestConfig();
            this.uRoot.active = true;
        } else if (data == "enterGame") {
            cc.director.loadScene("Helloworld");
        }
    }
    /**
     * 从服务器加载测试配置
     */
    private loadTestConfig() {
        // const defaultTestAssets = [
        //     {
        //         aurl: "https://example.com/assets/texture1.zip",  // 资源下载URL
        //         amd5: "a1b2c3d4e5f6789012345678901234567",      // 资源MD5校验值
        //         size: 1024000,                                    // 资源大小(字节)
        //         atv: '{"ver":"1.0.1","desc":"纹理资源更新"}'      // 版本信息JSON字符串
        //     }
        // ];

        const configUrl = "http://192.168.120.58:3000/HelloHot/hotTestConfig.json";
        console.log(`[GameUpgrade] 正在从服务器加载测试配置: ${configUrl}`);
        this.labTestInfo.string = `000 ${configUrl}`;

        Http.obj.Send(configUrl, (status: number, data: any) => {
            this.labTestInfo.string = `111 status = ${status}`;
            if (status === 200 && data) {
                try {
                    this.labTestInfo.string = `222`;
                    const config = JSON.parse(data);
                    console.log(`[GameUpgrade] 成功获取测试配置:`, config);
                    this.labTestInfo.string = `222-1 ${JSON.stringify(config)}`;

                    // 检查配置格式
                    if (config.testAssets && Array.isArray(config.testAssets)) {
                        this.labTestInfo.string = `222-2`;
                        this.Assets(config.testAssets);
                        this.DownloadAssets();
                    } else {
                        this.labTestInfo.string = `222-3`;
                        console.error(`[GameUpgrade] 测试配置格式错误，缺少testAssets数组`);
                    }
                } catch (error) {
                    this.labTestInfo.string = `333`;
                    console.error(`[GameUpgrade] 解析测试配置失败:`, error);
                }
            } else {
                this.labTestInfo.string = `444`;
                console.error(`[GameUpgrade] 获取测试配置失败，状态码: ${status}`);
            }
        }, null, HttpType.GET);
    }
}